import random
from datetime import datetime
# 一、定义一个学生Student类。有下面的类属性：
# 1 姓名 name
# 2 年龄 age
# 3 成绩 score（语文，数学，英语) [每课成绩的类型为整数]
"""class Student:
    def __init__(self,name,age,score:dict):
        self.name = name
        self.age = age
        self.score = score
    # 类方法：
    #  1 获取学生的姓名：get_name() 返回类型:str
    def get_name(self):
        return f"学生姓名:{self.name}"

    # 2 获取学生的年龄：get_age() 返回类型:int
    def get_age(self):
        return f"学生{self.name}的年龄：{int(self.age)}"

    # 3 返回3门科目中最高的分数。get_course() 返回类型:int
    def get_course(self):
        s_max = 0
        for k,v in self.score.items():
            if v > s_max:
                s_max = int(v)
                s_c = k
        return f"{self.name}的科目{s_c}的分数最高为{s_max}"
    # 4 将每个实例学生对象写进txt文件里，要持久保存
    # 举例：{"姓名":"a","年龄":29,"成绩":{"语文":99,"数学":100,"英语":85}
    def write_stu(self):
        with open("day7_01_student.txt","a",encoding="utf-8") as f:
            dict_stu = {"姓名":self.name,"年龄":self.age,"成绩":self.score}
            f.write(f"{dict_stu}\n")
    # 5 获取所有学生的信息
    def obtain_stu(self):
        with open("day7_01_student.txt","r",encoding="utf-8") as f:
            return f.read()
    # 写好类以后，可以定义2个同学测试下:
    # zm = Student('zhangming',20,[69,88,100])
zm = Student("zhangming",20,{"语文":69,"数学":88,"英语":100})
xm = Student("小明",18,{"语文":88,"数学":100,"英语":66})
# zm.write_stu()
# xm.write_stu()
# print(zm.obtain_stu())
# print(zm.get_course())
# print(xm.get_course())
# print(xm.get_age())
# print(xm.get_name())"""

# 二、定义一个字典类：dictclass。完成下面的功能：
"""class Dictclass:
    def __init__(self,dict_:dict):
        self.dict_ = dict_
    # 1 删除某个key
    def del_key(self,key):
        dict_1 = {}
        if key in list(self.dict_.keys()):
            for k,v in self.dict_.items():
                if k != key:
                    dict_1[k] = v
            print("删除成功咯！")
        else:
            for k,v in self.dict_.items():
                if k != key:
                    dict_1[k] = v
            print(f"你要删除的键 '{key}' 不存在！！！")
        return dict_1
    # 2 判断某个键是否在字典里，如果在返回键对应的值，不存在则返回"not found"
    def judge_key(self,key):
        if key in list(self.dict_.keys()):
            return f"该{key}对应的值为'{self.dict_[key]}'"
        else:
            return "not found"
    # 3 返回键组成的列表：返回类型;(list)
    def ret_list(self):
        list_ = []
        for v in self.dict_.values():
            list_.append(v)
        return list_
    # 4 合并字典，并且返回合并后字典的values组成的列表。返回类型:(list)\
    def merge_dic(self,dict_:dict):
        dict_1 = {}
        for k,v in self.dict_.items():
            dict_1[k] = v
        for k,v in dict_.items():
            dict_1[k] = v
        print(f"合并成功，合并后的字典为:{dict_1}")
        return list(dict_1.values())
dic1 = Dictclass({"姓名":"杨","年龄":22,"地址":"沈阳"})
# print(dic1.del_key("姓名"))
# print(dic1.del_key("说话"))
# print(dic1.judge_key("姓名"))
# print(dic1.judge_key("说话"))
# print(dic1.merge_dic({"姓名1": "丁", "年龄1": 18}))"""

# 三、定义一个列表的操作类：Listinfo
"""class Listinfo:
    def __init__(self,list_:list):
        self.list_ = list_
    # 包括的方法:
    # 1 列表元素添加: add_key(keyname) [keyname:字符串或者整数类型]
    def add_key(self,keyname:str or int):
        self.list_.append(keyname)
        return self.list_
    # 2 列表元素取值：get_key(num) [num:整数类型]
    def get_key(self,num:int):
        if num < len(self.list_) + 1:
            result = self.list_[num - 1]
            return result
        else:
            return "您要取得元素不存在！"
    # 3 列表合并：update_list(list) [list:列表类型]
    def update_list(self,list_):
        self.list_.extend(list_)
        return self.list_
    # 4 删除并且返回最后一个元素：del_key()
    def del_key(self):
        count = 0
        for i in self.list_:
            count += 1
            if count == len(self.list_):
                self.list_.remove(i)
                return i

list_ = Listinfo(["说话","look","my","eyes",7,3,13])
# print(list_.add_key(15))
# print(list_.get_key(5))
# print(list_.update_list([1, 2, 99]))
# print(list_.del_key())"""

# 四、做一个学生点名系统，系统里支持：存入学生、更改学生、删除学生、点到学生姓名方法
"""class StuCall:
    def store_name(self):
        with open("day7_04_student.txt","r",encoding="utf-8") as f:
            all_date = f.read()
            name = input("请输入要存入的名字：")
        if name not in all_date:
            age = input("请输入年龄：")
            address = input("请输入地址：")
            phone = input("请输入号码：")
            with open("day7_04_student.txt", "a", encoding="utf-8") as f:
                f.write(f"{name},{age},{address},{phone}\n")
            return f"您存入名字为'{name}'的信息:年龄:{age},地址:{address},号码:{phone}成功"
        else:
            return f"您要存入的名字为'{name}'的信息已存在！"
    # 更改学生（姓名、年龄、家庭地址、手机号）：可以修改学生内容的任意一个字段
    def change_name(self):
        with open("day7_04_student.txt","r",encoding="utf-8") as f:
            all_date = f.read()
        name_old = input("请输入你要修改的学生姓名：")
        if name_old in all_date:
            with open("day7_04_student.txt", "r", encoding="utf-8") as f:
                list_date = f.readlines()
            for i in list_date:
                if name_old in i.strip():
                    print(i.strip())
                    old_ = input("请输入您要修改的内容：")
                    new_ = input("请输入您修改后的内容：")
                    new_str = i.replace(old_,new_)
                    list_date.remove(i)
                    list_date.append(new_str)
            with open("day7_04_student.txt","w",encoding="utf-8") as f:
                f.writelines(list_date)
            return f"您修改的学生'{name_old}'的信息成功！"
        else:
            return "您要修改的名字不存在！"
    # 删除学生：删除的学生将不在展示
    def del_stu(self):
        with open("day7_04_student.txt","r",encoding="utf-8") as f:
            all_date = f.read()
        name = input("请输入要删除信息的学生名字：")
        if name in all_date:
            with open("day7_04_student.txt", "r", encoding="utf-8") as f:
                list_date = f.readlines()
            for i in list_date:
                if name in i.strip():
                    list_date.remove(i)
            with open("day7_04_student.txt","w",encoding="utf-8") as f:
                f.writelines(list_date)
            return f"您已成功删除{name}的信息！"
        else:
            return f"您要删除的{name}信息不存在！"
    # 展示全部学生：可以看到全部的学生姓名
    def display_name(self):
        show_list  = []
        with open("day7_04_student.txt", "r", encoding="utf-8") as f:
            list_date = f.readlines()
        if list_date:
            print("====下方展示学生姓名=====")
            for i in list_date:
                list_ = i.strip()
                list_1 = list_.split(",")
                str_1 = list_1[0]
                if str_1:
                    show_list.append(str_1)
            print(f"{show_list}")
            return "====上方展示学生姓名====="
        else:
            return "学生为空，请赶快添加哦！"
    # 学生姓名：随机抽取任意一个存在的学生信息，然后打印：到！。举例： 刘闯到！
    def random_name(self):
        show_list = []
        with open("day7_04_student.txt", "r", encoding="utf-8") as f:
            list_date = f.readlines()
        for i in list_date:
            list_ = i.strip()
            list_1 = list_.split(",")
            list_2 = list_1[0]
            if list_2:
                show_list.append(list_2)
        name = random.choice(show_list)
        print("========点名区域============")
        print(f"{name}到！")
        print("========点名区域============")
        return "点名完毕"
    def exit_stu(self):
        print("欢迎下次光临")

# while True:
#     print("欢迎来到学生点名系统！")
stu = StuCall()
while True:
    print("欢迎来到学生点名系统！")
    print("功能菜单：","1、存入学生","2、修改学生","3、删除学生","4、展示全部学生","5、随机点名","6、退出系统")
    key = input("请输入功能对应菜单：")
    if key == "1":
        print(stu.store_name())
    elif key == "2":
        print(stu.change_name())
    elif key == "3":
        print(stu.del_stu())
    elif key == "4":
        print(stu.display_name())
    elif key == "5":
        print(stu.random_name())
    elif key == "6":
        print("感谢您的使用！！！")
        break
    else:
        print("您输入的序号有误，请再次输入")"""

# 五、点餐管理系统
# 1》、餐馆可以新增菜品、下架菜品、修改菜品
# 2》、每个菜品，都有对应的库存，所有菜品的库存均为999，每出一道菜，库存-1
# 菜品有对应的价格，餐厅老板定义价格每道菜不允许超过15元，没有小数单位，均为整数
# 3》、餐馆后台有点赞系统，能够收集客户对菜品的喜好，0~5分
# 4》、有菜品评分提报功能，对平均分数（菜品总分/打分人数）低于3分的菜品进行强制下架；
"""dict_ = {}
class Order:
    def add_(self):
        name = input("请输入新增菜品：")
        if name not in list(dict_.keys()):
            price = input("请输入价格：")
            if price <= "15":
                dict_[name] = {"价格":price,"库存":999}
                print(f"添加菜品{name}成功！")
            else:
                print(f"价格{price}超过15,不可以哦！")
        else:
            print("该菜品已存在！")
    def eat_(self):
        name = input("请输入要出的菜：")
        if name in list(dict_.keys()):
            for k,v in dict_.items():
                if k == name:
                    v["库存"] -= 1
                    dict_[name] = {"价格":v["价格"],"库存":v["库存"]}
                    # list_ = list("价格:{价格},库存:{库存}".format(**v))
                    # print(list_)
            print(dict_)
    def like_(self):
        list_ = []
        for i in list(dict_.keys()):
            list_.append(i)
        print(list_)
            


dian = Order()
while True:
    key = input("请输入选项：")
    if key == "1":
        dian.add_()
    elif key == "2":
        dian.eat_()"""


# 六、定义一个桌子类（Desk），包含长（length）、宽（width）、高（height）属性，
"""class Desk:
    def __init__(self,length,width,height):
        self.length = length
        self.width = width
        self.height = height
    # 包含一个打印桌子信息属性的方法（showInfo）。
    def showInfo(self):
        print(f"{self.name}的长为{self.length}米,宽为{self.width}米,高为{self.height}米")
#实例化2个桌子对象，为其赋予不同的属性值，
# 并调用showInfo方法，输出每个桌子的信息。
d1 = Desk(1,2,3)
d1.name = "桌子1"
d1.showInfo()
d2 = Desk(2,3,6)
d2.name = "桌子2"
d2.showInfo()
"""

# 七、定义一个用户类(User),用户名(username)和密码(password)是这个类的属性。
"""class User:
    def __init__(self,username,password):
        self.username = username
        self.passwors = password"""

# 八、定义一个计算器类，有加减乘除四个方法
"""class Calculator:
    def add(self,*args):
        sum = 0
        for i in args:
            sum += i
        return sum
    def sub(self,num1,num2):
        return num1 - num2
    def mult(self,num1,num2):
        return num1 * num2
    def div(self,num1,num2):
        if num2 == 0:
            return "除数不能为0"
        else:
            return num1 / num2
ca = Calculator()
print(ca.sub(2, 1))
print(ca.div(2, 0))
print(ca.div(5, 2))
print(ca.add(1,2,3,4,5))"""

# 九、创建一个名为Person的类，具有以下属性和方法：
# 属性：name（姓名），age（年龄）
# 方法：greet()，打印出一句问候语，包括该人的姓名和年龄
"""class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def greet(self):
        print(f"{self.age}的{self.name},hello啊，你今天吃饭了吗？")
pe = Person("小丁",18)
pe.greet()"""

# 十、定义一个图书管理系统类，图书可以新增、修改、删除，要求新增的每个图书都加到txt文本里，数据持久化
# 新增：图书名、作者名称、新建年月日
# 修改：图书名、作者名称、新建年月日
# 删除：图书删掉，且不在展示
# 查看：全量查询，精确查询，需要用户传入形参来控制返回结果
"""class Library:
    # 新增：图书名、作者名称、新建年月日
    def add(self,book):
        with open("day7_10_books.txt","r",encoding="utf-8") as f:
            all_date = f.read()
        if f"图书:{book}" not in all_date:
            name = input("请输入作者名字：")
            time = datetime.now()
            with open("day7_10_books.txt","a",encoding="utf-8") as f:
                f.write(f"图书:{book},作者:{name},创建时间:{time}\n")
            print(f"新增{book}的信息成功")
        else:
            print("您要新增的图书已存在！！！！")
    # 修改：图书名、作者名称、新建年月日
    def modify_book(self,book):
        with open("day7_10_books.txt","r",encoding="utf-8") as f:
            all_date = f.read()
        if f"图书:{book}" in all_date:
            with open("day7_10_books.txt","r",encoding="utf-8") as f:
                list_book = f.readlines()
                # print(list_book)
            count = 0
            for i in list_book:
                if count == 1:
                    break
                print("外层")
                if f"图书:{book}" in i:
                    print("修改书名，请输入a","修改作者请输入b","结束修改请输入q",sep = "\n")
                    key = input("请输入选项：")
                    if key == "a":
                        book_new = input("请输入新的书名：")
                        str_1 = i.replace(f"图书:{book}",f"图书:{book_new}")
                        list_book.remove(i)
                        list_book.append(str_1)
                        with open("day7_10_books.txt", "w", encoding="utf-8") as f:
                            f.writelines(list_book)

                    elif key == "b":
                        str_ = ""
                        list_ = i.split(",")
                        name_new = input("请输入新的作者名字：")
                        list_[1] = f"作者:{name_new}"
                        list_book.remove(i)
                        for j in list_:
                            str_ += j + ","
                        list_book.append(str_[:-1])
                        list_book.append("\n")
                        with open("day7_10_books.txt", "w", encoding="utf-8") as f:
                            f.writelines(list_book)
                        # str_1 = ""
                        # list_1 = i.split(",")
                        # list_1[2] = f"创建时间{datetime.now()}\n"
                        # list_book.remove(i)
                        # for k in list_1:
                        #     str_1 += k
                        # list_book.append(str_1)
                    count += 1

            print(f"修改{book}的信息成功！")
        else:
            print("您要修改的图书不存在！！！！")
    def del_book(self,book):
        with open("day7_10_books.txt","r",encoding="utf-8") as f:
            all_date = f.read()
        if f"图书:{book}" in all_date:
            with open("day7_10_books.txt","r",encoding="utf-8") as f:
                list_book = f.readlines()
                for i in list_book:
                    if f"图书:{book}" in i:
                        list_book.remove(i)
                with open("day7_10_books.txt","w",encoding="utf-8") as f:
                    f.writelines(list_book)
                print(f"删除图书{book}的信息成功！！！！")
        else:
            print("你要删除的图书不存在！！！")
    def display(self):
        list_ = []
        with open("day7_10_books.txt","r",encoding="utf-8") as f:
            list_book = f.readlines()
            for i in list_book:
                a = i.strip()
                if a:
                    list_.append(a)
            print(list_)
            
bk = Library()
while True:
    print("欢迎来到图书管理系统！")
    print("功能菜单","1、新增","2、修改","3、删除","4、查看","5、退出")
    key = input("输入功能对应序号：")
    if key == "1":
        book = input("请输入书名：")
        bk.add(book)
    elif key == "2":
        book = input("请输入你要修改的图书：")
        print(bk.modify_book(book))
    elif key == "3":
        book = input("请输入要删除的图书：")
        print(bk.del_book(book))
    elif key == "4":
        bk.display()
    elif key == "5":
        print("感谢您的使用！！！")
    else:
        print("输入的序号有误，请再次输入！")"""

# 十一、创建一个名为"Car"的类，该类具有"品牌"和"颜色"属性。
# 创建一个"start_engine"方法，该方法打印出"启动汽车引擎！"的消息。
# 创建一个"stop_engine"方法，该方法打印出"关闭汽车引擎！"的消息
"""class Car:
    def __init__(self,grand,color):
        self.grand = grand
        self.color = color
    def start_engine(self):
        print(f"{self.grand}品牌的{self.color}色的汽车，启动汽车引擎！")
    def stop_engine(self):
        print(f"{self.grand}品牌的{self.color}色的汽车，关闭汽车引擎！")
car1 = Car("保时捷","流光银")
car1.start_engine()
car1.stop_engine()"""

# 十二、淘宝商家后台，可以上架商品、下架商品，功能如下：
#  （1） 可以添加商品，商家添加完的商品会存到商品列表
#  1.1  商品要有名称、sku、价格
#  （2） 可以修改商品信息：名称、sku、价格
#  （3） 可以对商品进行下架，下架后的商品不再展示
"""dict_ = {}
class Backend:
    def add_(self):
        name = input("请输入添加的商品名字：")
        if name not in list(dict_.keys()):
            sku = input("请输入商品库存量：")
            price = input("请输入商品价格：")
            dict_[name] = {"库存":sku,"价格":price}
            print("商品信息添加成功！")
        else:
            print(f"该商品{name}已经存在！")
    def alter_(self):
        name_old = input("请输入要修改的商品名字：")
        if name_old in list(dict_.keys()):
            dict_.pop(name_old)
            name_new = input("请输入修改后的商品名字：")
            sku_new = input("请输入修改后的商品库存：")
            price_new = input("请输入修改后的商品价格：")
            dict_[name_new] = {"库存":sku_new,"价格":price_new}
            print(f"您已修改{name_old}的信息")
        else:
            print(f"您要修改的商品{name_old}不存在")
    def del_(self):
        name = input("请输入你要下架的商品名称：")
        if name in list(dict_.keys()):
            dict_.pop(name)
            print(f"下架商品{name}成功")
        else:
            print(f"您要下架的商品不存在！！！")
    def display_(self):
        print("=======展示区域==============")
        for k,v in dict_.items():
            print(f"商品{k}的信息为","库存:{库存},价格:{价格}".format(**v))
        print("=======展示区域==============")

bend = Backend()

while True:
    print("1，新增","2.修改","3.删除","4.查看","5.退出")
    key = input("输入选项：")
    if key == "1":
        bend.add_()
    elif key =="2":
        bend.alter_()
    elif key == "3":
        bend.del_()
    elif key == "4":
        bend.display_()
    elif key == "5":
        print("再见！")
        break
    else:
        print("序号错误！")"""




# 十三、定义一个人类
# 1.小明和小美都爱跑步
# 2.小美体重45.0公斤
# 3.小明体重75.0公斤
# 4.每次跑步都会减少0.5公斤
# 5.每次吃东西都会增加1公斤
"""class Person:
    def __init__(self,weight):
        self.weight = weight
    def run1(self):
        self.weight -= 0.5
        return self.weight
    def eat1(self):
        self.weight += 1
        return self.weight
xiaoming = Person(75)
xiaomei = Person(45)
print(xiaoming.run1())
print(xiaoming.run1())"""

# 十四、士兵瑞恩有一把ak47
# 士兵可以开火（开火扣动的是扳机）
# 枪能够发射子弹（把子弹打出去）
# 抢能够装子弹–增加子弹数量
# 要求没子弹，需要输出没有子弹了，且发射失败
"""class Gun:
    def __init__(self,bullet):
        self.bullet = bullet
    def shoot(self):
        if self.bullet == 0:
            return "没有子弹了，发射失败"
        else:
            print("发射子弹---------------->")
            self.bullet -= 1
            return f"剩余子弹数{self.bullet}"
    def reload(self):
        print("装弹成功")
        self.bullet += 10
        return f"现枪内子弹数量为：{self.bullet}"
ak47 = Gun(50)
for i in range(55):
    print(ak47.shoot())
print(ak47.reload())"""